<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>索要照片信息统计 - n8n工作流监控系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', '微软雅黑', 'PingFang SC', 'Hiragino Sans GB', 'Heiti SC', 'WenQuanYi Micro Hei', 'Noto Sans CJK SC', 'Source Han Sans CN', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .back-btn {
            background: white;
            color: #667eea;
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
            font-size: 1em;
            font-weight: bold;
            cursor: pointer;
            margin-top: 15px;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            text-decoration: none;
            display: inline-block;
        }
        
        .back-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
        }
        
        .main-section {
            background: white;
            border-radius: 15px;
            padding: 40px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        .evaluate-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 20px 50px;
            border-radius: 50px;
            font-size: 1.3em;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            margin: 30px auto;
            display: inline-block;
        }
        
        .evaluate-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 25px rgba(0,0,0,0.3);
        }
        
        .evaluate-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }
        
        .progress-section {
            display: none;
            margin: 30px 0;
        }
        
        .progress-bar {
            width: 100%;
            height: 30px;
            background: #e9ecef;
            border-radius: 15px;
            overflow: hidden;
            margin-bottom: 15px;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            width: 0%;
            transition: width 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }
        
        .progress-text {
            text-align: center;
            color: #666;
            font-size: 1.1em;
            margin-top: 10px;
        }
        
        .stats-section {
            display: none;
            margin: 30px 0;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin: 20px 0;
        }
        
        .stat-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
        }
        
        .stat-card .label {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 10px;
        }
        
        .stat-card .value {
            font-size: 2em;
            font-weight: bold;
            color: #667eea;
        }
        
        .stat-card.warning .value {
            color: #f59e0b;
        }
        
        .stat-card.success .value {
            color: #10b981;
        }
        
        .action-buttons {
            display: none;
            margin: 30px 0;
            gap: 20px;
            justify-content: center;
        }
        
        .action-btn {
            background: white;
            color: #667eea;
            border: 2px solid #667eea;
            padding: 15px 40px;
            border-radius: 25px;
            font-size: 1.1em;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
            text-decoration: none;
            display: inline-block;
        }
        
        .action-btn:hover {
            background: #667eea;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
        
        .messages-section {
            display: none;
            margin-top: 30px;
        }
        
        .section-title {
            font-size: 1.5em;
            color: #333;
            margin-bottom: 20px;
            text-align: left;
        }
        
        .messages-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 30px;
        }
        
        .message-column {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
        }
        
        .column-title {
            font-size: 1.2em;
            font-weight: bold;
            margin-bottom: 15px;
            text-align: left;
        }
        
        .photo-related {
            color: #f59e0b;
        }
        
        .message-item {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            border-left: 4px solid #f59e0b;
        }
        
        .message-content {
            font-size: 0.95em;
            color: #333;
            margin-bottom: 10px;
            word-break: break-all;
        }
        
        .message-meta {
            font-size: 0.85em;
            color: #666;
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid #e9ecef;
        }
        
        .message-timestamp {
            font-size: 0.8em;
            color: #999;
            margin-top: 5px;
            font-style: italic;
        }
        
        .message-timestamp::before {
            content: "🕒 ";
        }
        
        .loading {
            text-align: center;
            color: #666;
            padding: 40px;
            font-size: 1.2em;
        }
        
        .error {
            text-align: center;
            color: #ef4444;
            padding: 40px;
            font-size: 1.2em;
        }
        
        /* 🔥 新增：搜索框样式 */
        .search-container {
            position: sticky;
            top: 0;
            z-index: 100;
            margin: 20px 0;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
            border: 2px solid #e5e7eb;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .search-box {
            display: flex;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        .search-input-wrapper {
            flex: 1;
            min-width: 300px;
            position: relative;
        }
        
        .search-input {
            width: 100%;
            padding: 12px 45px 12px 15px;
            border: 2px solid #667eea;
            border-radius: 25px;
            font-size: 1em;
            outline: none;
            transition: all 0.3s;
        }
        
        .search-input:focus {
            border-color: #764ba2;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .search-icon {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #667eea;
            font-size: 1.2em;
        }
        
        .search-stats {
            color: #667eea;
            font-weight: 600;
            font-size: 0.95em;
            padding: 8px 20px;
            background: white;
            border-radius: 20px;
            border: 2px solid #667eea;
        }
        
        .clear-search-btn {
            padding: 10px 25px;
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white;
            border: none;
            border-radius: 20px;
            font-size: 0.95em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 2px 5px rgba(239, 68, 68, 0.3);
        }
        
        .clear-search-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(239, 68, 68, 0.4);
        }
        
        .clear-search-btn:disabled {
            background: #d1d5db;
            cursor: not-allowed;
            box-shadow: none;
            transform: none;
        }
        
        /* 🔥 新增：排序按钮样式 */
        .sort-time-btn {
            padding: 10px 25px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 20px;
            font-size: 0.95em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 2px 5px rgba(102, 126, 234, 0.3);
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .sort-time-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(102, 126, 234, 0.4);
        }
        
        .sort-time-btn:active {
            transform: translateY(0);
        }
        
        .sort-time-btn .sort-icon {
            font-size: 1.1em;
            transition: transform 0.3s;
        }
        
        .sort-time-btn[data-order="desc"] .sort-icon {
            transform: rotate(180deg);
        }
        
        .message-item.hidden {
            display: none !important;
        }
        
        /* 消息列表容器最小高度，避免晃动 */
        #photoMessageList {
            min-height: 200px;
            transition: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📸 索要照片信息统计</h1>
            <p>AI智能评估索要照片相关消息</p>
            <a href="index.html" class="back-btn">← 返回主页</a>
        </div>
        
        <div class="main-section">
            <h2 id="mainTitle">索要照片信息统计</h2>
            <p id="mainDescription" style="color: #666; margin: 20px 0;">点击下方按钮开始评估所有候选人的索要照片相关消息</p>
            
            <div style="margin: 30px 0; display: flex; justify-content: center; align-items: center; gap: 20px;">
                <label for="messageLimit" style="font-size: 1.1em; font-weight: 500;">评估消息条数：</label>
                <select id="messageLimit" style="padding: 10px 20px; font-size: 1em; border: 2px solid #667eea; border-radius: 10px; background: white; cursor: pointer;">
                    <option value="0">全部消息</option>
                    <option value="10">最近10条</option>
                    <option value="20">最近20条</option>
                    <option value="50" selected>最近50条</option>
                    <option value="100">最近100条</option>
                    <option value="200">最近200条</option>
                </select>
            </div>
            
            <button class="evaluate-btn" id="evaluateBtn" onclick="startEvaluation()">
                🚀 开始评估
            </button>
            
            <!-- 进度条 -->
            <div class="progress-section" id="progressSection">
                <div class="progress-bar">
                    <div class="progress-fill" id="progressFill">0%</div>
                </div>
                <div class="progress-text" id="progressText">准备中...</div>
            </div>
            
            <!-- 统计结果 -->
            <div class="stats-section" id="statsSection">
                <h3>评估结果统计</h3>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="label">总候选人数</div>
                        <div class="value" id="totalCandidates">0</div>
                    </div>
                    <div class="stat-card">
                        <div class="label">总消息数</div>
                        <div class="value" id="totalMessages">0</div>
                    </div>
                    <div class="stat-card" style="border-left: 4px solid #3b82f6;">
                        <div class="label">🔑 关键词评估</div>
                        <div class="value" id="keywordEvaluatedCount">0</div>
                    </div>
                    <div class="stat-card success">
                        <div class="label">AI评估</div>
                        <div class="value" id="evaluatedCount">0</div>
                    </div>
                    <div class="stat-card warning" style="border-left: 4px solid #f59e0b;">
                        <div class="label">📸 照片消息</div>
                        <div class="value" id="photoMessages">0</div>
                    </div>
                    <div class="stat-card success">
                        <div class="label">📋 其他消息</div>
                        <div class="value" id="nonPhotoMessages">0</div>
                        <div class="sub-info" id="otherMessagesDetail" style="font-size: 0.75em; color: #999; margin-top: 8px;">
                            <!-- 动态显示详细说明 -->
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 操作按钮 -->
            <div class="action-buttons" id="actionButtons" style="display: none; flex-wrap: wrap; justify-content: center; gap: 20px;">
                <button class="action-btn" onclick="showMessages()" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-color: #667eea;">
                    📋 查看消息列表
                </button>
                <button class="action-btn" onclick="exportResults()" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; border-color: #10b981;">
                    📥 导出结果
                </button>
            </div>
            
            <!-- 消息分类 -->
            <div class="messages-section" id="messagesSection" style="display: none;">
                <h3 class="section-title">📨 要照片相关消息列表</h3>
                
                <!-- 🔥 新增：搜索框区域 -->
                <div class="search-container">
                    <div class="search-box">
                        <div class="search-input-wrapper">
                            <input 
                                type="text" 
                                id="messageSearchInput" 
                                class="search-input" 
                                placeholder="🔍 输入关键词搜索候选人姓名或消息内容..."
                                oninput="debouncedFilterMessages()"
                                autocomplete="off"
                            />
                            <span class="search-icon">🔍</span>
                        </div>
                        <div class="search-stats" id="searchStats">
                            显示全部消息
                        </div>
                        <button 
                            class="sort-time-btn" 
                            id="sortTimeBtn"
                            onclick="toggleSortOrder()"
                            data-order="desc"
                            title="点击切换时间排序"
                        >
                            <span class="sort-icon">⬇</span>
                            <span id="sortTimeText">时间降序</span>
                        </button>
                        <button 
                            class="clear-search-btn" 
                            id="clearSearchBtn"
                            onclick="clearSearch()"
                            disabled
                        >
                            ✕ 清除搜索
                        </button>
                    </div>
                </div>
                
                <div class="messages-grid">
                    <div class="message-column">
                        <div class="column-title photo-related" id="photoColumnTitle">📸 要照片相关消息</div>
                        <div id="photoMessageList"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        let evaluationData = null;
        
        // 🔥 新增：搜索和排序相关变量
        let allDisplayedMessages = []; // 保存所有当前显示的消息元素
        let totalMessageCount = 0; // 总消息数
        let searchDebounceTimer = null; // 防抖定时器
        let currentSortOrder = 'desc'; // 当前排序顺序: 'asc'升序(早到晚), 'desc'降序(晚到早)
        let originalPhotoMessages = []; // 保存原始照片消息数据用于排序
        
        // 页面加载时检测是否有评估数据
        window.addEventListener('DOMContentLoaded', async function() {
            console.log('========== 要照片页面加载开始 ==========');
            console.log('检测是否有已保存的评估数据...');
            
            await checkAndLoadExistingEvaluation();
        });
        
        // 检测并加载已有评估数据
        async function checkAndLoadExistingEvaluation() {
            try {
                console.log('调用 /api/evaluation-statistics API...');
                const response = await fetch('/api/evaluation-statistics');
                
                if (!response.ok) {
                    console.log('API调用失败:', response.status);
                    return;
                }
                
                const data = await response.json();
                console.log('API返回数据:', data);
                
                if (data.has_data) {
                    console.log('找到已保存的评估数据');
                    console.log('评估时间:', data.timestamp);
                    console.log('索要照片消息数:', data.photo_messages_count);
                    
                    // 加载评估数据
                    await loadEvaluationData(data);
                } else {
                    console.log('暂无已保存的评估数据');
                }
            } catch (error) {
                console.error('检测评估数据时发生错误:', error);
            }
        }
        
        // 加载评估数据
        async function loadEvaluationData(statistics) {
            try {
                console.log('========== 开始加载评估数据 ==========');
                
                // 修改：保留评估按钮和选择器，只更新标题和描述
                const evaluateBtn = document.getElementById('evaluateBtn');
                const messageLimit = document.getElementById('messageLimit');
                const messageLimitDiv = messageLimit.parentElement;
                const mainTitle = document.getElementById('mainTitle');
                const mainDescription = document.getElementById('mainDescription');
                
                // 确保评估按钮始终可见且可用
                if (evaluateBtn) {
                    evaluateBtn.style.display = 'inline-block';
                    evaluateBtn.disabled = false;
                    evaluateBtn.textContent = '🚀 开始评估';
                    console.log('已确保评估按钮可见且可用');
                }
                
                // 确保消息条数选择器可见
                if (messageLimitDiv) {
                    messageLimitDiv.style.display = 'flex';
                    console.log('已确保消息条数选择器可见');
                }
                
                if (mainTitle) {
                    mainTitle.textContent = '历史评估结果';
                    console.log('已更新主标题为历史评估结果');
                }
                
                if (mainDescription) {
                    mainDescription.textContent = '查看历史评估结果或继续进行新的评估';
                    console.log('已更新描述文字');
                }
                
                // 显示统计结果
                displayStats(statistics);
                console.log('已显示统计结果');
                
                // 显示操作按钮
                document.getElementById('actionButtons').style.display = 'flex';
                console.log('已显示操作按钮');
                
                // 构建evaluationData对象
                if (statistics.data && typeof statistics.data === 'object') {
                    evaluationData = statistics.data;
                    console.log('使用完整的评估数据:', evaluationData);
                } else {
                    evaluationData = {
                        success: true,
                        total_candidates: statistics.total_candidates || 0,
                        total_messages: statistics.total_messages || 0,
                        total_ai_messages: statistics.total_ai_messages || 0,
                        evaluated_count: statistics.evaluated_count || 0,
                        failed_count: statistics.failed_count || 0,
                        pending_count: statistics.pending_count || 0,
                        photo_messages_count: statistics.photo_messages_count || 0,
                        timestamp: statistics.timestamp,
                        all_evaluations: []
                    };
                    console.log('构建基础统计数据:', evaluationData);
                }
                
                console.log('========== 评估数据加载完成 ==========');
                
            } catch (error) {
                console.error('加载评估数据时发生错误:', error);
            }
        }
        
        // 开始评估
        async function startEvaluation() {
            console.log('开始评估流程 - 只评估要照片信息');
            const btn = document.getElementById('evaluateBtn');
            btn.disabled = true;
            btn.textContent = '评估中...';
            
            // 显示进度条
            document.getElementById('progressSection').style.display = 'block';
            
            try {
                // 获取选择的消息条数
                const messageLimit = parseInt(document.getElementById('messageLimit').value);
                console.log(`获取消息条数限制: ${messageLimit}`);
                
                // 调用后端API进行实时评估
                updateProgress(10, '正在连接服务器...');
                
                const apiUrl = `/api/batch-evaluate`;
                const requestBody = {
                    limit: messageLimit,
                    evaluate_type: 'photo'  // 只评估要照片信息
                };
                
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestBody)
                });
                
                console.log(`收到响应，状态码: ${response.status}`);
                if (!response.ok) {
                    console.error(`服务器返回错误: ${response.status} ${response.statusText}`);
                    throw new Error(`服务器返回错误: ${response.status} ${response.statusText}`);
                }
                
                updateProgress(30, '开始评估消息...');
                
                const data = await response.json();
                
                if (!data.success) {
                    console.error(`评估失败: ${data.error || '未知错误'}`);
                    throw new Error(data.error || '评估失败');
                }
                
                // 模拟进度更新
                updateProgress(50, '评估进行中...');
                await new Promise(resolve => setTimeout(resolve, 200));
                
                updateProgress(70, '正在整理结果...');
                await new Promise(resolve => setTimeout(resolve, 200));
                
                updateProgress(90, '即将完成...');
                await new Promise(resolve => setTimeout(resolve, 200));
                
                // 保存完整的评估数据
                evaluationData = data;
                
                updateProgress(100, '评估完成！');
                
                // 显示统计结果
                displayStats(data);
                
                // 显示操作按钮
                document.getElementById('actionButtons').style.display = 'flex';
                
                btn.textContent = '✅ 评估完成';
                
            } catch (error) {
                console.error('评估过程中发生错误', error);
                alert(`评估失败: ${error.message}`);
                btn.disabled = false;
                btn.textContent = '🚀 开始评估';
                document.getElementById('progressSection').style.display = 'none';
            }
        }
        
        // 更新进度
        function updateProgress(percent, text) {
            document.getElementById('progressFill').style.width = percent + '%';
            document.getElementById('progressFill').textContent = percent + '%';
            document.getElementById('progressText').textContent = text;
        }
        
        // 显示统计
        function displayStats(data) {
            console.log('========== 前端接收数据 ==========');
            console.log('完整数据:', data);
            
            const totalCandidates = data.total_candidates || 0;
            const totalAIMessages = data.total_ai_messages || 0;
            const keywordEvaluatedCount = data.keyword_evaluated_count || 0; // 🔥 关键词评估通过数量
            const evaluatedCount = data.evaluated_count || 0;
            const photoMessagesCount = data.photo_messages_count || 0;
            const nonPhotoMessagesCount = data.non_salary_messages_count || (evaluatedCount - photoMessagesCount) || 0;
            
            // 🔥 新增：计算误匹配和普通消息
            // 照片统计页面：误匹配 = 关键词评估 - 照片
            const mismatchedCount = keywordEvaluatedCount - photoMessagesCount;
            // 普通消息 = 总消息 - 关键词评估（关键词未通过）
            const normalCount = totalAIMessages - keywordEvaluatedCount;
            
            console.log('[统计显示] 误匹配消息:', mismatchedCount);
            console.log('[统计显示] 普通消息:', normalCount);
            console.log('[统计显示] 其他消息总数:', nonPhotoMessagesCount);
            console.log('[统计显示] 验证: 误匹配 + 普通 = 其他:', mismatchedCount + normalCount, '=', nonPhotoMessagesCount);
            
            document.getElementById('totalCandidates').textContent = totalCandidates;
            document.getElementById('totalMessages').textContent = totalAIMessages;
            document.getElementById('keywordEvaluatedCount').textContent = keywordEvaluatedCount; // 🔥 关键词评估数
            document.getElementById('evaluatedCount').textContent = evaluatedCount;
            document.getElementById('photoMessages').textContent = photoMessagesCount;
            document.getElementById('nonPhotoMessages').textContent = nonPhotoMessagesCount;
            
            // 🔥 新增：显示其他消息的详细说明
            const otherMessagesDetail = document.getElementById('otherMessagesDetail');
            if (otherMessagesDetail) {
                otherMessagesDetail.textContent = `${mismatchedCount}条误匹配 + ${normalCount}条普通消息`;
                console.log('[统计显示] 其他消息详细说明已更新');
            }
            
            document.getElementById('statsSection').style.display = 'block';
        }
        
        // 显示消息分类
        function showMessages() {
            console.log('========== [要照片页面] 开始显示消息列表 ==========');
            
            // 显示消息列表
            const messagesSection = document.getElementById('messagesSection');
            messagesSection.style.display = 'block';
            
            const photoList = document.getElementById('photoMessageList');
            
            photoList.innerHTML = '';
            
            if (!evaluationData) {
                console.log('[要照片页面] evaluationData为空，显示暂无数据');
                photoList.innerHTML = '<div class="loading">暂无消息数据</div>';
                return;
            }
            
            // 从all_evaluations过滤要照片相关消息
            const allEvaluations = evaluationData.all_evaluations || [];
            console.log('[要照片页面] 所有评估数据:', allEvaluations.length);
            
            const photoMessages = [];
            
            allEvaluations.forEach(msg => {
                const evaluation = msg.evaluation || {};
                // 修复：字段名应该是is_photo_request，不是is_photo_related
                const isPhoto = evaluation.is_photo_request || false;
                
                console.log('[要照片页面] 检查消息:', {
                    content: msg.content?.substring(0, 30),
                    is_photo_request: evaluation.is_photo_request,
                    photo_score: evaluation.photo_score
                });
                
                if (isPhoto) {
                    photoMessages.push(msg);
                }
            });
            
            console.log(`[要照片页面] 要照片相关消息数: ${photoMessages.length}`);
            
            // 更新列标题显示数量
            document.getElementById('photoColumnTitle').textContent = `📸 要照片相关消息 (${photoMessages.length})`;
            
            // 显示要照片相关消息
            photoMessages.forEach(msg => {
                const messageItem = document.createElement('div');
                messageItem.className = 'message-item';
                
                const evaluation = msg.evaluation || {};
                const content = msg.content || '无内容';
                const candidateName = msg.candidate_name || `#${msg.candidate_id || '未知'}`;
                const score = evaluation.photo_score || evaluation.score || 0;
                const reason = evaluation.photo_reason || evaluation.reason || '无评估理由';
                const timestamp = msg.created_at || '';
                
                console.log(`[要照片页面] 消息时间戳: ${timestamp}`);
                
                messageItem.innerHTML = `
                    <div class="message-content">${content}</div>
                    <div class="message-meta">
                        候选人 ${candidateName} | 
                        评分: ${score}分 | 
                        ${reason}
                        <button class="view-chat-btn" 
                                data-candidate-id="${msg.candidate_id}" 
                                data-candidate-name="${candidateName.replace(/"/g, '&quot;')}"
                                style="margin-left: 15px; padding: 5px 15px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                                       color: white; border: none; border-radius: 15px; cursor: pointer; font-size: 0.9em; 
                                       transition: all 0.3s; box-shadow: 0 2px 5px rgba(0,0,0,0.2);"
                                onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 10px rgba(0,0,0,0.3)';"
                                onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 5px rgba(0,0,0,0.2)';">
                            💬 查看聊天记录
                        </button>
                    </div>
                    <div class="message-timestamp">${formatTimestamp(timestamp)}</div>
                `;
                
                // 为按钮添加点击事件监听器
                const chatBtn = messageItem.querySelector('.view-chat-btn');
                if (chatBtn) {
                    chatBtn.addEventListener('click', function(e) {
                        e.preventDefault();
                        const candidateId = this.getAttribute('data-candidate-id');
                        const candidateName = this.getAttribute('data-candidate-name');
                        viewChatHistory(candidateId, candidateName);
                    });
                }
                
                photoList.appendChild(messageItem);
            });
            
            if (photoList.children.length === 0) {
                photoList.innerHTML = '<div class="loading">暂无要照片相关消息</div>';
            }
            
            console.log('========== [要照片页面] 消息列表显示完成 ==========');
            console.log(`[要照片页面] 总结: 显示了${photoMessages.length}条要照片消息`);
            
            // 🔥 新增：保存所有消息元素供搜索使用
            allDisplayedMessages = document.querySelectorAll('.message-item');
            totalMessageCount = allDisplayedMessages.length;
            
            // 保存原始消息数据用于排序
            originalPhotoMessages = photoMessages;
            
            console.log(`[要照片页面] 已保存 ${allDisplayedMessages.length} 个消息元素供搜索使用`);
            
            // 重置搜索框
            const searchInput = document.getElementById('messageSearchInput');
            if (searchInput) {
                searchInput.value = '';
            }
            updateSearchStats(totalMessageCount, totalMessageCount);
            const clearBtn = document.getElementById('clearSearchBtn');
            if (clearBtn) {
                clearBtn.disabled = true;
            }
            
            console.log(`[要照片页面] 搜索功能已初始化，总消息数: ${totalMessageCount}`);
        }
        
        // 时间格式化函数
        function formatTimestamp(timestamp) {
            if (!timestamp) {
                console.log('[时间格式化] 时间戳为空');
                return '时间未知';
            }
            
            try {
                // 支持多种时间格式
                let date;
                if (timestamp instanceof Date) {
                    date = timestamp;
                } else if (typeof timestamp === 'string') {
                    // 替换空格为T以支持ISO格式
                    const isoFormat = timestamp.replace(' ', 'T');
                    date = new Date(isoFormat);
                } else {
                    date = new Date(timestamp);
                }
                
                // 检查日期是否有效
                if (isNaN(date.getTime())) {
                    console.warn('[时间格式化] 无效的时间戳:', timestamp);
                    return timestamp; // 返回原始值
                }
                
                // 格式化为本地时间
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                
                const formatted = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                console.log(`[时间格式化] 原始: ${timestamp} -> 格式化: ${formatted}`);
                return formatted;
            } catch (e) {
                console.error('[时间格式化] 格式化失败:', e, '原始值:', timestamp);
                return timestamp || '时间未知';
            }
        }
        
        /**
         * 查看聊天历史记录
         */
        function viewChatHistory(candidateId, candidateName) {
            console.log('[查看聊天] ========== 准备查看聊天记录 ==========');
            console.log('[查看聊天] 候选人ID:', candidateId);
            console.log('[查看聊天] 候选人姓名:', candidateName);
            
            if (!candidateId) {
                console.error('[查看聊天] 候选人ID为空');
                alert('无法获取候选人信息');
                return;
            }
            
            // 构建目标URL，包含from参数以便返回
            const currentPage = 'photo_only_detail.html';
            const targetUrl = `user_chat.html?candidate_id=${candidateId}&from=${encodeURIComponent(currentPage)}`;
            
            console.log('[查看聊天] 目标URL:', targetUrl);
            console.log('[查看聊天] 跳转到聊天记录页面...');
            
            // 跳转到聊天记录页面
            window.location.href = targetUrl;
        }
        
        // 导出评估结果
        async function exportResults() {
            console.log('========== 开始导出 ==========');
            
            if (!evaluationData) {
                console.log('错误: evaluationData为空');
                alert('请先进行评估');
                return;
            }
            
            try {
                const response = await fetch('/api/export-evaluations', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        evaluations: evaluationData.all_evaluations || [],
                        statistics: {
                            total_candidates: evaluationData.total_candidates,
                            total_messages: evaluationData.total_messages,
                            photo_messages_count: evaluationData.photo_messages_count,
                            evaluated_count: evaluationData.evaluated_count,
                            failed_count: evaluationData.failed_count,
                            pending_count: evaluationData.pending_count
                        }
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`导出失败: ${response.status}`);
                }
                
                const result = await response.json();
                
                if (result.success) {
                    alert(`导出成功！\n文件路径: ${result.file_path}`);
                    console.log('导出成功:', result.file_path);
                } else {
                    throw new Error(result.error || '导出失败');
                }
                
            } catch (error) {
                console.error('导出失败:', error);
                alert(`导出失败: ${error.message}`);
            }
        }
        
        /**
         * 🔥 新增：防抖处理的搜索函数
         */
        function debouncedFilterMessages() {
            console.log('[搜索过滤] 触发防抖搜索');
            
            if (searchDebounceTimer) {
                clearTimeout(searchDebounceTimer);
            }
            
            searchDebounceTimer = setTimeout(() => {
                console.log('[搜索过滤] 执行搜索');
                filterMessages();
            }, 300);
        }
        
        /**
         * 🔥 新增：搜索过滤功能
         */
        function filterMessages() {
            console.log('========== [搜索过滤] 开始过滤消息 ==========');
            
            const searchInput = document.getElementById('messageSearchInput');
            if (!searchInput) {
                console.error('[搜索过滤] ❌ 搜索框元素不存在');
                return;
            }
            
            if (!allDisplayedMessages || allDisplayedMessages.length === 0) {
                console.warn('[搜索过滤] ⚠️ 没有可搜索的消息');
                return;
            }
            
            const searchTerm = searchInput.value.trim().toLowerCase();
            console.log(`[搜索过滤] 搜索关键词: "${searchTerm}"`);
            console.log(`[搜索过滤] 总消息数: ${totalMessageCount}`);
            
            if (!searchTerm) {
                console.log('[搜索过滤] 搜索词为空，显示所有消息');
                allDisplayedMessages.forEach(item => {
                    if (item && item.classList) {
                        item.classList.remove('hidden');
                    }
                });
                updateSearchStats(totalMessageCount, totalMessageCount);
                const clearBtn = document.getElementById('clearSearchBtn');
                if (clearBtn) clearBtn.disabled = true;
                console.log(`[搜索过滤] ✅ 已显示全部 ${totalMessageCount} 条消息`);
                return;
            }
            
            const clearBtn = document.getElementById('clearSearchBtn');
            if (clearBtn) clearBtn.disabled = false;
            
            let visibleCount = 0;
            let hiddenCount = 0;
            
            requestAnimationFrame(() => {
                allDisplayedMessages.forEach((item, index) => {
                    if (!item || !item.classList) {
                        console.warn(`[搜索过滤] ⚠️ 消息元素 #${index} 无效`);
                        return;
                    }
                    
                    try {
                        const messageContent = item.querySelector('.message-content')?.textContent.toLowerCase() || '';
                        const messageMeta = item.querySelector('.message-meta')?.textContent.toLowerCase() || '';
                        const searchableText = `${messageContent} ${messageMeta}`;
                        
                        const isMatch = searchableText.includes(searchTerm);
                        
                        if (isMatch) {
                            item.classList.remove('hidden');
                            visibleCount++;
                            if (visibleCount <= 3) {
                                console.log(`[搜索过滤] ✅ 匹配 #${visibleCount}: ${messageContent.substring(0, 30)}...`);
                            }
                        } else {
                            item.classList.add('hidden');
                            hiddenCount++;
                        }
                    } catch (error) {
                        console.error(`[搜索过滤] ❌ 处理消息 #${index} 时出错:`, error);
                    }
                });
                
                updateSearchStats(visibleCount, totalMessageCount);
                
                console.log('[搜索过滤] ========== 过滤完成 ==========');
                console.log(`[搜索过滤] 📊 统计结果:`);
                console.log(`  - 显示消息: ${visibleCount} 条`);
                console.log(`  - 隐藏消息: ${hiddenCount} 条`);
                console.log(`  - 总消息数: ${totalMessageCount} 条`);
                console.log(`  - 匹配率: ${((visibleCount / totalMessageCount) * 100).toFixed(2)}%`);
                
                if (visibleCount === 0) {
                    console.warn('[搜索过滤] ⚠️ 未找到匹配的消息');
                }
            });
        }
        
        /**
         * 🔥 新增：更新搜索统计信息
         */
        function updateSearchStats(visibleCount, totalCount) {
            const searchStats = document.getElementById('searchStats');
            
            if (!searchStats) {
                console.error('[搜索统计] ❌ 统计元素不存在');
                return;
            }
            
            if (visibleCount === totalCount) {
                searchStats.textContent = `显示全部消息 (${totalCount})`;
                searchStats.style.borderColor = '#667eea';
                searchStats.style.color = '#667eea';
                console.log(`[搜索统计] 显示全部消息: ${totalCount} 条`);
            } else {
                searchStats.textContent = `找到 ${visibleCount} / ${totalCount} 条消息`;
                searchStats.style.borderColor = visibleCount > 0 ? '#10b981' : '#f59e0b';
                searchStats.style.color = visibleCount > 0 ? '#10b981' : '#f59e0b';
                console.log(`[搜索统计] 过滤结果: ${visibleCount} / ${totalCount} 条`);
            }
        }
        
        /**
         * 🔥 新增：清除搜索
         */
        function clearSearch() {
            console.log('[搜索过滤] 清除搜索条件');
            
            const searchInput = document.getElementById('messageSearchInput');
            if (!searchInput) {
                console.error('[搜索过滤] ❌ 搜索框元素不存在');
                return;
            }
            
            searchInput.value = '';
            filterMessages();
            searchInput.blur();
            
            console.log('[搜索过滤] ✅ 搜索已清除，已显示所有消息');
        }
        
        /**
         * 🔥 新增：按时间排序消息
         */
        function sortMessagesByTime(messages, order) {
            console.log(`[时间排序] 开始排序，顺序: ${order}, 消息数: ${messages.length}`);
            
            if (!messages || messages.length === 0) {
                console.warn('[时间排序] ⚠️ 消息列表为空');
                return [];
            }
            
            const sortedMessages = [...messages];
            
            sortedMessages.sort((a, b) => {
                const timeA = new Date(a.created_at || 0).getTime();
                const timeB = new Date(b.created_at || 0).getTime();
                
                if (order === 'asc') {
                    return timeA - timeB;
                } else {
                    return timeB - timeA;
                }
            });
            
            if (sortedMessages.length > 0) {
                console.log('[时间排序] 前3条消息时间:');
                sortedMessages.slice(0, 3).forEach((msg, idx) => {
                    const time = formatTimestamp(msg.created_at);
                    console.log(`  ${idx + 1}. ${time}`);
                });
            }
            
            console.log('[时间排序] ✅ 排序完成');
            return sortedMessages;
        }
        
        /**
         * 🔥 新增：切换排序顺序
         */
        function toggleSortOrder() {
            console.log('========== [时间排序] 切换排序顺序 ==========');
            console.log(`[时间排序] 当前顺序: ${currentSortOrder}`);
            
            currentSortOrder = currentSortOrder === 'asc' ? 'desc' : 'asc';
            console.log(`[时间排序] 新顺序: ${currentSortOrder}`);
            
            const sortBtn = document.getElementById('sortTimeBtn');
            const sortText = document.getElementById('sortTimeText');
            
            if (sortBtn && sortText) {
                sortBtn.setAttribute('data-order', currentSortOrder);
                
                if (currentSortOrder === 'asc') {
                    sortText.textContent = '时间升序';
                    sortBtn.title = '当前：早→晚，点击切换';
                    console.log('[时间排序] 按钮更新为：时间升序 ⬆');
                } else {
                    sortText.textContent = '时间降序';
                    sortBtn.title = '当前：晚→早，点击切换';
                    console.log('[时间排序] 按钮更新为：时间降序 ⬇');
                }
            }
            
            if (originalPhotoMessages.length > 0) {
                console.log('[时间排序] 重新渲染消息列表...');
                
                const sortedMessages = sortMessagesByTime(originalPhotoMessages, currentSortOrder);
                rerenderPhotoMessages(sortedMessages);
                
                const searchInput = document.getElementById('messageSearchInput');
                if (searchInput && searchInput.value.trim()) {
                    console.log('[时间排序] 重新应用搜索过滤...');
                    setTimeout(() => filterMessages(), 100);
                }
                
                console.log('[时间排序] ✅ 消息列表重新渲染完成');
            } else {
                console.warn('[时间排序] ⚠️ 没有消息数据可排序');
            }
            
            console.log('[时间排序] ========== 排序切换完成 ==========');
        }
        
        /**
         * 🔥 新增：重新渲染要照片消息列表
         */
        function rerenderPhotoMessages(photoMessages) {
            console.log('[消息渲染] 开始重新渲染要照片消息列表...');
            console.log(`[消息渲染] 要照片消息: ${photoMessages.length} 条`);
            
            const photoList = document.getElementById('photoMessageList');
            photoList.innerHTML = '';
            
            photoMessages.forEach((msg, index) => {
                const messageItem = document.createElement('div');
                messageItem.className = 'message-item photo';
                
                const evaluation = msg.evaluation || {};
                const content = msg.content || '无内容';
                const candidateName = msg.candidate_name || `#${msg.candidate_id || '未知'}`;
                const score = evaluation.photo_score || evaluation.score || 0;
                const reason = evaluation.photo_reason || evaluation.reason || '无评估理由';
                const timestamp = msg.created_at || '';
                
                messageItem.innerHTML = `
                    <div class="message-content">${content}</div>
                    <div class="message-meta">
                        候选人 ${candidateName} | 
                        评分: ${score}分 | 
                        ${reason}
                        <button class="view-chat-btn" 
                                data-candidate-id="${msg.candidate_id}" 
                                data-candidate-name="${candidateName.replace(/"/g, '&quot;')}"
                                style="margin-left: 15px; padding: 5px 15px; background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); 
                                       color: white; border: none; border-radius: 15px; cursor: pointer; font-size: 0.9em; 
                                       transition: all 0.3s; box-shadow: 0 2px 5px rgba(0,0,0,0.2);"
                                onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 10px rgba(0,0,0,0.3)';"
                                onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 5px rgba(0,0,0,0.2)';">
                            💬 查看聊天记录
                        </button>
                    </div>
                    <div class="message-timestamp">${formatTimestamp(timestamp)}</div>
                `;
                
                const photoBtn = messageItem.querySelector('.view-chat-btn');
                if (photoBtn) {
                    photoBtn.addEventListener('click', function(e) {
                        e.preventDefault();
                        const candidateId = this.getAttribute('data-candidate-id');
                        const candidateName = this.getAttribute('data-candidate-name');
                        viewChatHistory(candidateId, candidateName);
                    });
                }
                
                photoList.appendChild(messageItem);
            });
            
            if (photoList.children.length === 0) {
                photoList.innerHTML = '<div class="loading">暂无要照片相关消息</div>';
            }
            
            allDisplayedMessages = document.querySelectorAll('.message-item');
            totalMessageCount = allDisplayedMessages.length;
            
            console.log(`[消息渲染] ✅ 渲染完成，总消息数: ${totalMessageCount}`);
        }
    </script>
</body>
</html>
